package com.ruben.simplescaffold.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * 可以从applicationContext获取bean
 *
 * @author <achao1441470436@gmail.com>
 * @since 2020/11/12 0012 20:40
 */
@Lazy(false)
@Component("SpringContextHolder")
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {
    private SpringContextHolder() {
    }

    private static final String ERROR_MESSAGE = "applicationContext尚未注入";
    private static ApplicationContext applicationContext;

    public static <T> T getBean(Class<T> type) {
        return Optional.ofNullable(applicationContext)
                .orElseThrow(() -> new IllegalStateException(ERROR_MESSAGE))
                .getBean(type);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        return (T) Optional.ofNullable(applicationContext)
                .orElseThrow(() -> new IllegalStateException(ERROR_MESSAGE))
                .getBean(name);
    }

    @Override
    public void destroy() {
        applicationContext = null;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.applicationContext = applicationContext;
    }


}
